package com.cloud.pay.payment;

import com.cloud.pay.constant.PayStatusEnum;
import com.cloud.pay.entity.Payment;
import com.cloud.pay.service.PaymentService;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.egzosn.pay.wx.api.WxPayService;
import com.egzosn.pay.wx.bean.WxPayMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WxPayBackHandler implements PayMessageHandler<WxPayMessage, PayService> {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PayNotifyer payNotifyer;

    /**
     * 微信支付回调的处理
     *
     * @param wxPayMessage 支付消息
     * @param contextMap    上下文
     * @param payService 支付服务
     * @throws PayErrorException 支付错误异常
     */
    @Override
    public PayOutMessage handle(WxPayMessage wxPayMessage, Map<String, Object> contextMap, PayService payService) throws PayErrorException {
        //交易状态
        if (WxPayService.SUCCESS.equals(wxPayMessage.getPayMessage().get(WxPayService.RETURN_CODE))){
            if (WxPayService.SUCCESS.equals(wxPayMessage.getResultCode())) {
                Payment payment = paymentService.getByOrderNo(wxPayMessage.getAppid(), wxPayMessage.getOutTradeNo());
                if (payment != null) {
                    payment.setTradeNo(wxPayMessage.getTransactionId());
                    payment.setPayStatus(PayStatusEnum.PAID.getCode());
                    paymentService.updateById(payment);

                    if (payNotifyer.send(payment).successful()) {
                        return payService.getPayOutMessage(WxPayService.SUCCESS, "OK");
                    }
                }
            }
        }
        return  payService.getPayOutMessage(WxPayService.FAILURE, WxPayService.FAILURE);
    }
}
